package com.qf.business.course.core.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.business.course.core.dao.CourseTypeDao;
import com.qf.business.course.core.service.CourseTypeGuigeService;
import com.qf.business.course.core.service.CourseTypeService;
import com.qf.commons.core.utils.CommonsUtils;
import com.qf.data.course.entity.CourseType;
import com.qf.data.course.entity.CourseTypeGuige;
import com.qf.data.course.vo.input.TypeGuigesInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程分类表(CourseType)表服务实现类
 *
 * @author makejava
 * @since 2022-09-22 09:52:55
 */
@Service("courseTypeService")
public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeDao, CourseType> implements CourseTypeService {

    @Autowired
    private CourseTypeGuigeService courseTypeGuigeService;

    @Override
    public boolean save(CourseType entity) {
        //查询父级分类
        CourseType parent = this.getById(entity.getPid());
        if(parent != null){
            //设置当前分类的tag
            entity.setTag(parent.getTag() != null ?
                    parent.getTag() + CommonsUtils.id2Str(parent.getId(), 4) : CommonsUtils.id2Str(parent.getId(), 4));
            entity.setStatus(parent.getStatus() + 1);
        } else {
            entity.setStatus(1);
        }
        return super.save(entity);
    }

    /**
     * 修改指定type的关联规格
     * @param typeGuigesInput
     * @return
     */
    @Override
    @Transactional
    public int updateTypeGuiges(TypeGuigesInput typeGuigesInput) {
        //根据类型id 删除 关联记录
        Map map = new HashMap<>();
        map.put("tid", typeGuigesInput.getTid());
        courseTypeGuigeService.removeByMap(map);

        //批量保存关联规格信息
        List<CourseTypeGuige> typeGuies = typeGuigesInput.getGids().stream().map(
                gid -> new CourseTypeGuige()
                        .setTid(typeGuigesInput.getTid())
                        .setGid(gid)
        ).collect(Collectors.toList());
        courseTypeGuigeService.saveBatch(typeGuies);
        return 1;
    }
}